<template>
  <div>
    <el-collapse-transition>
      <div v-show="btnGroup.search" class="main-box search-box">
        <el-form
          class="troila-form"
          ref="searchInfo"
          :model="searchObj"
          :inline="true"
          label-width="100px"
        >
          <el-form-item
            label="角色名称"
            prop="roleName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入角色名称"
              v-model="searchObj.roleName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="权限字符"
            prop="roleCode"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入权限字符"
              v-model="searchObj.roleCode"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="角色状态"
            prop="state"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="请选择角色状态"
              v-model="searchObj.state"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in statusList"
                :key="index"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" class="troila-select-inline">
            <el-date-picker
              v-model="time"
              v-setwidth
              placeholder="请选择"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="changeDate"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="searchBtn">
            <el-button class="cancelBtn" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>
    <div class="troila-group">
      <select-group
        v-model="btnGroup"
        :row="allTitle"
        :row-choose="chooseTitle"
        @rowChange="
          (arr) => {
            chooseTitle = arr
          }
        "
        @refresh="getList"
      />
    </div>
    <div class="main-box table-box">
      <div class="table-box-title ClearFloat">
        <i class="title-font">查询结果</i>
        <div class="troila-form">
          <el-button
            type="primary"
            v-limit="`system:roleManage:add`"
            @click="btnClick('add')"
            >新增</el-button
          >
          <!-- <el-button
            type="primary"
            v-limit="`system:roleManage:export`"
            @click="btnClick('export')"
            >导出</el-button
          > -->
          <el-button
            type="primary"
            v-limit="`system:roleManage:batchStart`"
            @click="btnClick('batchStart')"
            >批量启用</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:roleManage:batchStop`"
            @click="btnClick('batchStop')"
            >批量停用</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:roleManage:batchDel`"
            @click="btnClick('batchDel')"
            >批量删除</el-button
          >
        </div>
      </div>
      <unit-table
        v-if="!btnGroup.card"
        selection
        index
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <unit-cards
        v-if="btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
      />
      <pagination
        v-show="pager.total > pager.size"
        :pager="pager"
        @query="getList"
        ref="Pagerpagination"
      ></pagination>
    </div>
    <dialog-role v-model="showRole" @change="getList" />
  </div>
</template>
<script>
import dialogRole from './dialog/roleUser'
export default {
  name: 'roleManage',
  components: {
    dialogRole,
  },
  data() {
    return {
      searchObj: {
        roleName: '',
        roleCode: '',
        state: '',
        dateBegin: '',
        dateEnd: '',
      }, //搜索参数
      searchRes: {}, //搜索储存值
      loading: false,
      time: null, //时间组件值
      btnGroup: {
        //按钮组
        search: true,
        refresh: false,
        card: false,
      },
      pager: {
        // 页码
        total: 0,
        page: 1, //当前第几页
        size: 10, //每页显示的条数
      },
      dictionary: {
        // 字典信息
        // roleStatus: [
        //   { dictName: '启用', dictCode: '1' },
        //   { dictName: '停用', dictCode: '0' },
        // ],
      },
      allTitle: [
        // 全部可显示表头
        {
          label: '角色名称', //*表头名称
          code: 'roleName', //*对应数据项
          tooltip: true, //超出显示浮层
          sort: true, //是否显示排序
          width: 110, //最小宽
        },
        {
          label: '权限字符',
          code: 'roleCode',
          tooltip: true,
          sort: true,
          width: 110,
        },
        {
          label: '显示顺序',
          code: 'roleSort',
          sort: true,
        },
        {
          label: '角色状态',
          code: 'state',
          dict: 'roleStatus',
          style: {
            //该项style
            color: { value: '#FF4A4A', result: 0 },
          },
        },
        {
          label: '创建时间',
          code: 'createTime',
          tooltip: true,
          sort: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '创建人',
          code: 'createBy',
          tooltip: true,
          sort: true,
          width: 110,
        },
        {
          label: '修改时间',
          code: 'updateTime',
          tooltip: true,
          sort: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '修改人',
          code: 'updateBy',
          tooltip: true,
          sort: true,
          width: 110,
        },
        {
          label: '备注',
          code: 'remark',
          tooltip: true,
          width: 110,
        },
      ],
      chooseTitle: [
        //被选中显示表头
        'roleName',
        'roleCode',
        'roleSort',
        'state',
        'createTime',
      ],
      tableData: [],
      tableOperation: [
        //表格操作
        // *code 对应图标, label 对应浮层显示文字, show 判断是否显示, color 图标颜色
        { code: 'edit', limit: 'system:roleManage:edit' },
        // {
        //   code: 'authority',
        //   label: '数据权限',
        //   limit: 'system:roleManage:authority'
        //   show: row => {
        //     return true
        //   }
        // },
        {
          code: 'user',
          label: '分配用户',
          limit: 'system:roleManage:user',
          show: (row) => {
            return true
          },
        },
        {
          code: 'start',
          label: '启用',
          limit: 'system:roleManage:start',
          show: (row) => {
            return row.state == 0
          },
        },
        {
          code: 'stop',
          label: '停用',
          limit: 'system:roleManage:stop',
          color: '#D13633',
          show: (row) => {
            return row.state == 1
          },
        },
        { code: 'delete', limit: 'system:roleManage:delete', color: '#D13633' },
      ],
      selection: [], //表格选中行
      showRole: false, //弹窗显示-分配角色
    }
  },
  computed: {
    tableTitle() {
      //表格表头
      return this.allTitle.filter(
        (item) => this.chooseTitle.indexOf(item.code) > -1
      )
    },
    statusList() {
      let list = this.$store.state.dictionary.role_status
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'role_status')
      }
      this.dictionary.roleStatus = list
      return list ? list : []
    },
  },
  created() {
    this.submitSearch()
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true
      let param = {
        pageNum: this.pager.page,
        pageSize: this.pager.size,
        ...this.searchRes,
      }
      setTimeout(() => {
        this.loading = false
        this.pager.total = 4
        this.tableData = [{}, {}, {}, {}]
      }, 100)
      return
      this.API.roleManage
        .pageList(param)
        .then((res) => {
          if (res.code == 1) {
            this.loading = false
            this.pager.total = res.data.total ? res.data.total : 0
            this.tableData = res.data.records
          } else {
            this.loading = false
          }
        })
        .catch((error) => {
          this.loading = false
        })
    },
    // 日期控件操作
    changeDate() {
      if (this.time) {
        this.searchObj.dateBegin = this.time[0]
        this.searchObj.dateEnd = this.time[1]
      } else {
        this.searchObj.dateBegin = ''
        this.searchObj.dateEnd = ''
      }
    },
    // 重置
    resetForm() {
      this.$refs.searchInfo.resetFields()
      this.searchRes = {}
      // this.searchObj = {}
      this.pager.page = 1
      this.getList()
    },
    // 搜索
    submitSearch() {
      this.searchRes = { ...this.searchObj }
      this.searchObj.dateBegin = ''
      this.searchObj.dateEnd = ''
      this.pager.page = 1
      this.getList()
    },
    // 按钮操作
    btnClick(method) {
      // console.log(method)
      let text = ''
      switch (method) {
        case 'add':
          this.$router.push({
            name: 'addRole',
          })
          return
        case 'batchStart':
          text = '启用'
          break
        case 'batchStop':
          text = '停用'
          break
        case 'batchDel':
          text = '删除'
          break
        default:
          return
      }
      let name = this.selection.map((v) => `${v.roleName}`)
      this.selection.length > 0
        ? this.$confirmFn(
            `您确定${text}以下角色吗？<div>${name.join('、')}</div>`,
            '提示',
            {
              callback: (action, instance) => {
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  // console.log(this.selection)
                  let idArr = []
                  this.selection.map((v) => {
                    idArr.push(v.id)
                  })
                  let postData = {
                    ids: idArr.join(','),
                    status:
                      method == 'batchStart'
                        ? 1
                        : method == 'batchStop'
                        ? 0
                        : 2,
                  }
                  // console.log(postData)
                  this.API.roleManage.updateStatus(postData).then((res) => {
                    if (res.code == 1) {
                      this.$alertFn.success(`${text}角色成功`)
                      this.getList()
                    } else {
                      this.$alertFn.error(`${text}角色失败`)
                      this.getList()
                    }
                  })
                }
              },
            }
          )
        : this.$alertFn.error(`请选择需要${text}的数据 ！`)
    },
    // 表格操作
    tableReturn(method, { row, prop, order, selection }) {
      // console.log(method, row, prop, order, selection)
      let text = ''
      switch (method) {
        case 'edit':
          this.$router.push({
            name: 'editRole',
            params: { roleId: this.encode(row.id), row: row },
          })
          return
        case 'user':
          this.showRole = row
          return
        case 'selection':
          this.selection = [...selection]
          return
        case 'start':
          text = '启用'
          break
        case 'stop':
          text = '停用'
          break
        case 'delete':
          text = '删除'
          break
        default:
          return
      }
      this.$confirmFn(
        `您确定要${text}角色<span class='light'>${row.roleName}</span>吗？`,
        '提示',
        {
          callback: (action, instance) => {
            if (action == 'cancel ') {
              return
            } else if (action == 'confirm') {
              // console.log(method, row)
              let postData = {
                ids: row.id,
                status: method == 'start' ? 1 : method == 'stop' ? 0 : 2,
              }
              // console.log(postData)
              this.API.roleManage.updateStatus(postData).then((res) => {
                if (res.code == 1) {
                  this.$alertFn.success(`${text}角色成功`)
                  this.getList()
                } else {
                  this.$alertFn.error(`${text}角色失败`)
                  this.getList()
                }
              })
            }
          },
        }
      )
    },
  },
  mounted() {},
  destroyed() {},
}
</script>
<style scoped>
</style>
